const Response = require("../../class/Response");

// 重连后玩家重登录
WSC.get('/bds/init/result', (wsclient, req, res)=>{
    mc.getOnlinePlayers().forEach(pl => {
        if (pl.isSimulatedPlayer()){return;}
        WSC.client?.sendJson(new Response()
            .setUrl("/bds/playerLogin")
            .setData({
                loginTime: new Date().getTime(),
                xuid: pl.xuid,
                uuid: pl.uuid,
                realName: pl.realName
            })
        );
    });
});

let isNewPlayer = {};
mc.listen("onPreJoin", (pl)=>{
    if (GMLIB_MC.hasPlayerNbt(pl.uuid)){
       join(pl);
    }else{
        isNewPlayer[pl.uuid] = true;
    }
});
mc.listen("onJoin", (pl)=>{
    if (isNewPlayer[pl.uuid]){
        delete isNewPlayer[pl.uuid];
        join(pl);
    }
});

function join(pl){
    if (pl.isSimulatedPlayer()){return;}
    WSC.client?.sendJson(new Response()
        .setUrl("/bds/playerLogin")
        .setData({
            loginTime: new Date().getTime(),
            xuid: pl.xuid,
            uuid: pl.uuid,
            realName: pl.realName,
        }),
        (req, res) =>{
            // '/bds/playerLogin/result'
            if (req.body.statusCode == 1){
                let pl = mc.getPlayer(req.body.data.xuid);
                if (pl == null){return;}
                pl.disconnect(`§c<${pl.realName}> 登录失败 | 不允许多设备登录同步服务器`);
                // 提示和日志信息由WS服务端广播
                return;
            }
        }
    );
}



mc.listen("onLeft", (pl)=>{
    if (pl.isSimulatedPlayer()){return;}
    WSC.client?.sendJson(new Response()
        .setUrl("/bds/playerLogout")
        .setData({
            logoutTime: new Date().getTime(),
            xuid: pl.xuid,
            uuid: pl.uuid,
            realName: pl.realName
        }),
        (req, res) =>{
            // '/bds/playerLogout/result'
            if (req.body.statusCode == 1){
                return;
            }
        }
    );
});